
local MsdkCommunityRender = app.mvc.createRenderClass(...)

local GapX = 63
local Padding = 15

--data 
function MsdkCommunityRender.create(node)
    local sprite = MsdkCommunityRender.extend(node or cc.CSLoader:createNode(Res.MsdkCommunityNode))
	if node == nil then
		ccui.Helper:doLayout(sprite)
	end
	sprite:init()
    return sprite
end

function MsdkCommunityRender:_readConfig()
    local communitys = GD:getTencentCommunity()
    local configs = {}
    local targetPlatform = app.channelAPI:getWGPlatform()
    for k, v in pairs(communitys) do
        if tonumber(v.communityId) == targetPlatform and tonumber(v.open) == 1 then
            table.insert(configs, {id = tonumber(v.ID), icon = v.icon, name = L(v.name), url = L(v.url)})
        end
    end
    table.sort(configs, function(a, b)
        return a.id < b.id
    end)

    return configs
end

function MsdkCommunityRender:init()
    self.super.init(self, nil) 

    local configs = self:_readConfig()
    if #configs == 0 then
        self._ui["Panel"]:setVisible(false)
        return
    end

    local offset = -5
    local gap = 15

    local size = self._ui["Panel/bg/Panel_1"]:getContentSize()
    local singleWidth  = size.width
    local minWidth = 165

    local num = #configs
    local nodeWidth = gap * (num - 1) + singleWidth * num
    local totalWidth = nodeWidth + 40
    if totalWidth < minWidth then
        totalWidth = minWidth
    end
    local nodes = {}
    table.insert(nodes, self._ui["Panel/bg/Panel_1"])
    for i =1, num - 1 do
        local node = self._ui["Panel/bg/Panel_1"]:clone()
        self._ui["Panel/bg"]:addChild(node)
        table.insert(nodes, node)
    end

    local _, oldHeight = self._ui["Panel/bg"]:getContentSize2()
    self._ui["Panel/bg"]:setContentSize(totalWidth, oldHeight)
    local startPos = (totalWidth - nodeWidth  + singleWidth)/2 + offset
    for k, v in pairs(nodes) do
        v:setPositionX(startPos)
        startPos = startPos + singleWidth + gap
        local icon = v:getChildByName("icon")
        local text = v:getChildByName("name")
        local config = configs[k]
        icon:loadTexture(Res.MsdkCommunityIconPath..config.icon..".png")
        text:setString(config.name)
        display.uiAddClick(v, function()
            self:_onClickIcon(config)
        end, true)
    end
end


function MsdkCommunityRender:addHideFunc(cb)
    display.nodeRemoveForNotHit(self._ui["Panel"], function()
        if cb then
            cb()
        end
    end)
end

function MsdkCommunityRender:refresh()
    if not self._data then
        return
    end
end

function MsdkCommunityRender:_onClickIcon(data)
    if data.id == 101 then
        --游戏中心
        app.channelAPI:openWeiXinDeeplink("DETAIL")
    elseif data.id == 103 then
        -- 公中号
        app.channelAPI:openURL("https://game.weixin.qq.com/cgi-bin/comm/openlink?noticeid=90214107&appid=wx467a8d593f07181c&url=https%3A%2F%2Fmp.weixin.qq.com%2Fmp%2Fprofile_ext%3Faction%3Dhome%26__biz%3DMzI4ODM4MDUxNg%3D%3D%26scene%3D124%23wechat_redirect#wechat_redirect")
    elseif data.id == 104 or data.id == 204 then
        --心悦
        local plat = 1
        if app:isIOS() then
            plat = 0
        end

        local ch = 1
        local area, reg = app.channelAPI:getArea()
        local msdkt = ""
        local platform = app.channelAPI:getWGPlatform()
        if platform == Enums.MSDK_PLATFORM.WX then
            ch = 2
            msdkt = app.channelAPI:getWxAccessToken()
        elseif platform == Enums.MSDK_PLATFORM.QQ then
            msdkt = app.channelAPI:getQqAccessToken()
            ch = 1
        end

        local ava = ""
        local myInfo = app.channelAPI:queryMyInfo()
        if myInfo then
            ava =  myInfo.pictureLarge
        end
        local nickName = UD.player.name
        local channelid = app.channelAPI:getTencentLoginChannelId()

        local gid = "1340"
        local pid = "75"
        local params = {
            gid = gid,
            pid = pid,
            reg = reg,
            plat = tostring(plat),
            ch = tostring(ch),
            area = tostring(area),
            part = tostring(app.session:getZoneId()),
            openid = app.channelAPI:getOpenId(),
            appid = app.channelAPI:getAppId(),
            role = tostring(UD.player.uid),
            msdkt = tostring(msdkt),
            t = tostring(os.time()),
            r = tostring(math.random(1000, 10000)),
            ava = ava,
            nick = UD.player.name,
            channelid = app.channelAPI:getTencentLoginChannelId(),
        }
        dump(params)

        local genCode = function()
            -- 1. 约定的参数构造为 json 串
            local paramsJson = json.encode(params) -- json 由接入方自行实现或导入第三方库
            print(paramsJson)
            -- 2. base64 编码上面的 json 串
            local base64String = cc.Crypto:encodeBase64(paramsJson, string.len(paramsJson)) --base64encode 由接入方自行实现或导入第三方库
            -- 3. 将上面 base64 串中+替换为-, /替换为_, 去掉=
            local base64String = string.gsub(base64String, "+", "-")
            local base64String = string.gsub(base64String, "/", "_")
            local base64String = string.gsub(base64String, "=", "")
            -- 4. 将约定密钥(由心悦提供)拼接在上面 base64 字符串后面再做 md5 得到 32 位消息摘要
            local md5String = cc.Crypto:MD5(base64String.."Bui1tin#t@Clu8", false) -- md5 由接入方自行实现或导入第三方库
            -- 5. 从第 9 位开始(包含第 9 位)到 24 位(包含 24 位)，截取上面 md5 字符串中间 16 位字符串得到签名码
            local signString = string.sub(md5String, 9, 24)
            -- 6. 将签名码附加到上面的 base64 串后面得到 code
            local code = base64String .. signString
            print(code)
            return code
        end
       
        local url = string.format("http://xinyue.qq.com/builtin_v31/index.html#/game?code=%s&gid=%s&pid=%s", genCode(), gid, pid)
        app.channelAPI:openURL(url)
        
    else
        if data.url and data.url ~= "" then
            app.channelAPI:openURL(data.url)
        end
    end
end



return MsdkCommunityRender
